package com.cy.order.service;

import com.cy.order.entity.Order;
import com.cy.order.feign.AccountClient;
import com.cy.order.feign.EasyIdClient;
import com.cy.order.feign.StorageClient;
import com.cy.order.mapper.OrderMapper;
import com.cy.order.util.JsonUtil;
import com.cy.order.util.RedisUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AccountClient accountClient;

    @Autowired
    private StorageClient storageClient;

    @Autowired
    private EasyIdClient easyIdClient;

    @Autowired
    private RedisUtil redisUtil;

    @Transactional          //控制本地事务
    @GlobalTransactional    //开启全局事务，只在第一个模块添加
    @Override
    public void create(Order order) {

        //生成订单id
        String s = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(s);
        order.setId(orderId);

        orderMapper.create(order);

        //订单模块生成订单后，需要远程调用减少商品库存和扣减账号金额
        //调用商品库存减少商品库存
        storageClient.decrease(order.getProductId(),order.getCount());
        //调用账户金额减少账户金额
        accountClient.decrease(order.getUserId(),order.getMoney());

        //在redis中也存一份订单数据
        redisUtil.set(""+orderId, JsonUtil.to(order));
    }

    @Override
    public Order findById(Long id) {
        /*
        * 1.从redis查询，如果有数据直接返回
        * 2.如果redis没有数据，从数据库查询
        * 3.将数据库查询的数据存入redis缓存
        * 4.返回
        * */
        //1.从redis查询
        String json = (String)redisUtil.get("" + id);

        //2.如果有数据，直接返回
        if (json != null){
            return JsonUtil.from(json,Order.class);
        }
        //3.如果redis没有数据，从数据库查询
        Order order = orderMapper.selectById(id);
        if (order == null){
            return order;
        }
        //4.把数据加入redis缓存
        redisUtil.set(""+id,JsonUtil.to(order));
        //5.返回
        return order;
    }
}
